#!/bin/bash

set -o errexit
set -o xtrace

test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions
cluster="scaling"

create_infra $namespace
spinup_pxc "$cluster" "$test_dir/conf/$cluster.yml"

desc 'scale up from 3 to 5'
cat_config "$test_dir/conf/$cluster.yml" \
    | sed -e 's/size: 3/size: 5/' \
    | kubectl_bin apply -f-

desc 'check if all 5 Pods started'
wait_for_running $cluster-pxc 5
sleep 15

desc 'check if PVC created'
compare_kubectl pvc/datadir-$cluster-pxc-3
compare_kubectl pvc/datadir-$cluster-pxc-4

desc 'check data consistency for new Pods'
compare_mysql_cmd "select-1" "SELECT * from myApp.myApp;" "-h $cluster-pxc-3.$cluster-pxc -uroot -proot_password"
compare_mysql_cmd "select-1" "SELECT * from myApp.myApp;" "-h $cluster-pxc-4.$cluster-pxc -uroot -proot_password"
sleep 15

desc 'check new Pods exists in ProxySQL'
run_mysql_local 'SELECT hostname FROM runtime_mysql_servers WHERE status="ONLINE";' "-h127.0.0.1 -P6032 -uproxyadmin -padmin_password" "$cluster-proxysql-0" \
    | grep "$cluster-pxc-3"
run_mysql_local 'SELECT hostname FROM runtime_mysql_servers WHERE status="ONLINE";' "-h127.0.0.1 -P6032 -uproxyadmin -padmin_password" "$cluster-proxysql-0" \
    | grep "$cluster-pxc-4"

desc 'scale down from 5 to 3'
apply_config "$test_dir/conf/$cluster.yml"
sleep 25

desc 'check if Pod deleted'
wait_for_delete pod/$cluster-pxc-3
wait_for_delete pod/$cluster-pxc-4

desc 'check if PVC not deleted'
compare_kubectl pvc/datadir-$cluster-pxc-3
compare_kubectl pvc/datadir-$cluster-pxc-4

desc 'check if Pod deleted from ProxySQL'
run_mysql_local 'SELECT hostname FROM runtime_mysql_servers WHERE status="ONLINE" AND hostgroup_id!=13;' "-h127.0.0.1 -P6032 -uproxyadmin -padmin_password" "$cluster-proxysql-0" \
    | ( grep "$cluster-pxc-3" && exit 1 || :)
run_mysql_local 'SELECT hostname FROM runtime_mysql_servers WHERE status="ONLINE" AND hostgroup_id!=13;' "-h127.0.0.1 -P6032 -uproxyadmin -padmin_password" "$cluster-proxysql-0" \
    | ( grep "$cluster-pxc-4" && exit 1 || :)

destroy $namespace
